import 'dart:convert';

import 'package:bbtree_flutter/home/discovery/DiscoveryEntity.Dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;

class ListenPage extends StatefulWidget {
  @override
  _ListenPageState createState() => _ListenPageState();
}

class _ListenPageState extends State<ListenPage> {
  double _itemPicWidth;
  List<DiscoveryTag> _tagList;
  List<DiscoveryItemEntity> _recommendList;
  List<DiscoveryItemEntity> _commonList = List();
  @override
  void initState() {
    super.initState();
    _getTagList();
    _getRecommendList();
    _getCommonList();
  }

  void _getCommonList() {
    rootBundle
        .loadString('assets/fake/json_discovery_audio_common_list.json')
        .then((json) {
      JsonDecoder decoder = new JsonDecoder();
      var result = decoder.convert(json);
      List contents = result['audios'];
      List<DiscoveryItemEntity> resultList =
          contents.map<DiscoveryItemEntity>((map) {
        return DiscoveryItemEntity.fromJson(map);
      }).toList();
      if (resultList != null) {
        setState(() {
          _commonList.addAll(resultList);
          _commonList.addAll(resultList);
          _commonList.addAll(resultList);
        });
      }
    });
  }

  void _getRecommendList() {
    rootBundle
        .loadString('assets/fake/json_discovery_audio_recommend.json')
        .then((json) {
      JsonDecoder decoder = new JsonDecoder();
      var result = decoder.convert(json);
      List contents = result['contents'];
      List<DiscoveryItemEntity> resultList =
          contents.map<DiscoveryItemEntity>((map) {
        return DiscoveryItemEntity.fromJson(map);
      }).toList();
      if (resultList != null) {
        setState(() {
          _recommendList = resultList;
        });
      }
    });
  }

  void _getTagList() {
    rootBundle
        .loadString('assets/fake/json_discovery_audio_tags.json')
        .then((json) {
      JsonDecoder decoder = new JsonDecoder();
      var result = decoder.convert(json);
      List tags = result['tags'];
      List<DiscoveryTag> resultList = tags.map<DiscoveryTag>((map) {
        return DiscoveryTag.fromJson(map);
      }).toList();
      if (resultList != null) {
        setState(() {
          _tagList = resultList;
        });
      }
    });
  }

  Widget _buildCatgoryText(String text) {
    return Container(
      margin: EdgeInsets.only(right: 10),
      height: 32,
      alignment: Alignment.center,
      padding: EdgeInsets.only(left: 14, right: 14),
      child: Text(
        text,
        style: TextStyle(fontSize: 14, color: const Color(0xff333333)),
      ),
      decoration: BoxDecoration(
          color: const Color(0xfff5f5f5),
          borderRadius: BorderRadius.all(Radius.circular(4))),
    );
  }

  Widget _buildCell(DiscoveryItemEntity entity) {
    return Container(
        width: _itemPicWidth,
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: <
            Widget>[
          Stack(
            children: <Widget>[
              Container(
                width: _itemPicWidth,
                height: _itemPicWidth,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(2)),
                    image: DecorationImage(
                        image: NetworkImage(entity.coverUrl[0]),
                        fit: BoxFit.cover),
                    border:
                        Border.all(color: const Color(0xffeeeeee), width: 0.5)),
              ),
              Container(
                padding: EdgeInsets.only(top: 2, right: 2),
                alignment: Alignment.topRight,
                child: Container(
                  padding: EdgeInsets.only(left: 4, right: 4),
                  decoration: BoxDecoration(
                      color: const Color(0xffFFBE16),
                      borderRadius: BorderRadius.all(Radius.circular(2))),
                  child: Text('VIP',
                      style: TextStyle(fontSize: 10, color: Colors.white)),
                ),
              ),
              Container(
                  padding: EdgeInsets.only(right: 4, bottom: 4),
                  height: _itemPicWidth,
                  alignment: Alignment.bottomRight,
                  child: Container(
                    padding: EdgeInsets.only(left: 6, right: 6),
                    decoration: BoxDecoration(
                        color: const Color(0x7f000000),
                        borderRadius: BorderRadius.all(Radius.circular(16))),
                    child: Text('02:25',
                        style: TextStyle(fontSize: 10, color: Colors.white)),
                  )),
            ],
          ),
          Text(
            entity.title,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: 14, color: const Color(0xff333333)),
          ),
          Text(
            entity.subTitle,
            maxLines: 1,
             overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: 12, color: const Color(0xff999999)),
          )
        ]));
  }

  Widget _buildRowLayout(List<DiscoveryItemEntity> entitys) {
    List<Widget> rows = List();
    for (int i = 0; i < entitys.length; i++) {
      DiscoveryItemEntity entity = entitys[i];
      rows.add(_buildCell(entity));
      if (i < entitys.length - 1) {
        rows.add(SizedBox(
          width: 4,
        ));
      }
    }
    return Container(
        margin: EdgeInsets.only(left: 15, right: 15, top: 20),
        child: Row(children: rows));
  }

  Widget _buildHotRecommentAudioWidget() {
    var length = _recommendList.length;
    int count = (length + 2) ~/ 3;
    int lastLineCount = length % 3 == 0 ? 3 : length % 3;
    List<Widget> rowWidget = List();
    rowWidget.add(Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        SizedBox(
          width: 15,
        ),
        Image.asset(
          'assets/images/recommend_music.png',
          width: 20,
          height: 20,
        ),
        SizedBox(
          width: 8,
        ),
        Text(
          "热门推荐",
          style: TextStyle(
              color: const Color(0xff333333),
              fontSize: 16,
              fontWeight: FontWeight.bold),
        )
      ],
    ));
    for (int i = 0; i < count; i++) {
      int start = i * 3;
      int end = i < count - 1 ? start + 3 : start + lastLineCount;
      rowWidget
          .add(_buildRowLayout(_recommendList.getRange(start, end).toList()));
    }
    rowWidget.add(
      Container(
        margin: EdgeInsets.only(top: 20),
        height: 15,color: const Color(0xfff5f5f5),));
    return Container(child: Column(children: rowWidget));
  }

  @override
  Widget build(BuildContext context) {
    _itemPicWidth = (MediaQuery.of(context).size.width - 15 * 2 - 4 * 2) / 3;
    List<Widget> child = List();
    if (_tagList != null && _tagList.length > 0) {
      var tagView = Container(
        height: 66,
        child: SingleChildScrollView(
          padding: EdgeInsets.only(left: 15, right: 15),
          scrollDirection: Axis.horizontal,
          child: Row(
            children: _tagList.map<Widget>((tag) {
              return _buildCatgoryText(tag.name);
            }).toList(),
          ),
        ),
      );
      child.add(tagView);
    }
    if (_recommendList != null && _recommendList.length > 0) {
      child.add(_buildHotRecommentAudioWidget());
    }
    if (_commonList != null&&_commonList.length>0) {
      List<Widget> commonWidgets = List();
      var length = _commonList.length;
      int count = (length + 2) ~/ 3;
      int lastLineCount = length % 3 == 0 ? 3 : length % 3;
      for (int i = 0; i < count; i++) {
        int start = i * 3;
        int end = i < count - 1 ? start + 3 : start + lastLineCount;
        commonWidgets
            .add(_buildRowLayout(_commonList.getRange(start, end).toList()));
      }
      child.addAll(commonWidgets);

    }
    return Container(
        color: Colors.white,
        alignment: Alignment.topLeft,
        child: ListView(
          children: child,
        ));
  }
}
